package com.hbm.eduservice.controller;


import com.hbm.commonutils.R;
import com.hbm.eduservice.client.VodClient;
import com.hbm.eduservice.entity.EduChapter;
import com.hbm.eduservice.entity.EduVideo;
import com.hbm.eduservice.service.EduVideoService;
import com.hbm.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-08-20
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService videoService;

    @Autowired
    private VodClient vodClient;
    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo){
        videoService.save(eduVideo);
        return R.ok();
    }

    //根据小节id查询
    @GetMapping("getVideoInfo/{videoId}")
    public R getVideoInfo(@PathVariable String videoId) {
        EduVideo video= videoService.getById(videoId);
        return R.ok().data("video",video);
    }

    //删除小节
    // TODO 后面这个方法需要完善：删除小节时候，同时把里面视频删除 已实现
    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable String id){
        //根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = videoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();

        //判断小节里面是否有视频id
//        if(!StringUtils.isEmpty(videoSourceId)) {
//            //根据视频id，远程调用实现视频删除
//            R result=vodClient.removeAlyVideo(videoSourceId);
//            if(result.getCode() == 20001) {
//                throw new GuliException(20001,"删除视频失败，熔断器...");
//            }
//        }
        //判断小节里面是否有视频id 上面方法保存 不知道具体原因  不存在视频是会报异常 所以直接删除就行了
//        if (!videoSourceId.isEmpty()){
//            vodClient.removeAlyVideo(videoSourceId);
//        }else {
//            throw new GuliException(20001,"删除视频失败，熔断器...");
//        }

        //上面方法不存在视频是会报异常 所以直接删除就行了
        if (!videoSourceId.isEmpty()) {
            vodClient.removeAlyVideo(videoSourceId);
        }

        //删除小节
        videoService.removeById(id);
        return R.ok();
    }

    //修改小节 TODO 已完成
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo){
        videoService.updateById(eduVideo);
        return R.ok();
    }


}

